package org.ruiyichen.guizhou.agr.ui.fragment;

import android.graphics.Rect;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.ruiyichen.guizhou.agr.R;
import org.ruiyichen.guizhou.agr.base.BaseFragment;
import org.ruiyichen.guizhou.agr.bean.MessageEvent;
import org.ruiyichen.guizhou.agr.bean.Response;
import org.ruiyichen.guizhou.agr.bean.mode.AgileDeviceModel;
import org.ruiyichen.guizhou.agr.bean.mode.HomeDeviceModel;
import org.ruiyichen.guizhou.agr.bean.mode.HomeMonitorModel;
import org.ruiyichen.guizhou.agr.bean.mode.WeatherModel;
import org.ruiyichen.guizhou.agr.config.Constant;
import org.ruiyichen.guizhou.agr.net.OkHttpManager;
import org.ruiyichen.guizhou.agr.ui.activity.HomeActivity;
import org.ruiyichen.guizhou.agr.ui.adapter.HomeDeviceRecyclerAdapter;
import org.ruiyichen.guizhou.agr.ui.adapter.HomeMonitorRecyclerAdapter;
import org.ruiyichen.guizhou.agr.ui.mineview.BToast;
import org.ruiyichen.guizhou.agr.utils.DimenUtils;
import org.ruiyichen.guizhou.agr.utils.ListUtil;
import org.ruiyichen.guizhou.agr.utils.StrUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

/**
 * 控制
 */
public class HomeAgileFragment extends BaseFragment implements View.OnClickListener {

    TextView tv_home_temperature,
            tv_home_weather,
            tv_home_address_and_data,
            tv_home_more,
            tv_home_agile;
    RecyclerView rv_home_monitor,
            rv_home_device;

    List<HomeMonitorModel> monitorModels = new ArrayList<>();
    HomeMonitorRecyclerAdapter monitorAdapter;

    List<HomeDeviceModel> deviceModels = new ArrayList<>();
    HomeDeviceRecyclerAdapter deviceAdapter;

    @Override
    public void onResume() {
        super.onResume();
        if (!getUserVisibleHint()) {
            return;
        }
        initData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            bHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    initData();
                }
            }, 500);
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.df_fragment_nav_home_agile, container, false);
            bOkHttpManager = new OkHttpManager(getActivity(), bHandler);
            EventBus.getDefault().register(this);
            initViews();
            initEvents();
            initData();
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        return mRootView;
    }

    private void initViews() {
        tv_home_temperature = mRootView.findViewById(R.id.tv_home_temperature);
        tv_home_weather = mRootView.findViewById(R.id.tv_home_weather);
        tv_home_address_and_data = mRootView.findViewById(R.id.tv_home_address_and_data);
        tv_home_more = mRootView.findViewById(R.id.tv_home_more);
        tv_home_more.setVisibility(View.GONE);

        tv_home_agile = mRootView.findViewById(R.id.tv_home_agile);
        final int size = DimenUtils.dip2px(getCustomActivity(), 1.0f);
        rv_home_monitor = mRootView.findViewById(R.id.rv_home_monitor);
        rv_home_monitor.setNestedScrollingEnabled(false);
        GridLayoutManager monitorManager = new GridLayoutManager(getCustomActivity(), 3);
        rv_home_monitor.setLayoutManager(monitorManager);
        rv_home_monitor.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int pos = parent.getChildAdapterPosition(view);
                if (pos / 3 > 0) {
                    outRect.top = size;
                }
                if (pos % 3 == 0) {
                    outRect.right = size;
                } else if (pos % 3 == 2) {
                    outRect.left = size;
                } else {
                    outRect.left = (int) (size * 0.5f);
                    outRect.right = (int) (size * 0.5f);
                }
            }
        });

//        List<HomeMonitorModel> monitorModels = new ArrayList<>();
//        monitorModels.add(new HomeMonitorModel(R.drawable.df_home_shuiwei, "水位", "0.2cm"));
//        monitorModels.add(new HomeMonitorModel(R.drawable.df_home_ph, "PH", "30"));
//        monitorModels.add(new HomeMonitorModel(R.drawable.df_home_ec, "EC", "6%"));
//        monitorModels.add(new HomeMonitorModel(R.drawable.df_home_guang_zhao_du, "光照度", "45000lux"));
//        monitorModels.add(new HomeMonitorModel(R.drawable.df_home_kqsd, "空气湿度", "61.5%"));
//        monitorModels.add(new HomeMonitorModel(R.drawable.df_home_fs, "风速", "2.1m/h"));
        monitorAdapter = new HomeMonitorRecyclerAdapter
                (getCustomActivity());
        monitorAdapter.setmDatas(monitorModels);
        rv_home_monitor.setAdapter(monitorAdapter);


        rv_home_device = (RecyclerView) mRootView.findViewById(R.id.rv_home_device);
        rv_home_device.setNestedScrollingEnabled(false);
        GridLayoutManager deviceManager = new GridLayoutManager(getCustomActivity(), 4);
        rv_home_device.setLayoutManager(deviceManager);
        rv_home_device.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int pos = parent.getChildAdapterPosition(view);
                if (pos / 4 > 0) {
                    outRect.top = size;
                }
                if (pos % 4 == 0) {
                    outRect.right = size;
                } else if (pos % 4 == 3) {
                    outRect.left = size;
                } else {
                    outRect.left = (int) (size * 0.5f);
                    outRect.right = (int) (size * 0.5f);
                }
            }
        });


//        deviceModels.add(new HomeDeviceModel("传感器数", "98"));
//        deviceModels.add(new HomeDeviceModel("控制数量", "30"));
//        deviceModels.add(new HomeDeviceModel("在线数量", "123"));
//        deviceModels.add(new HomeDeviceModel("触发报警", "2"));
        deviceAdapter = new HomeDeviceRecyclerAdapter(getCustomActivity
                ());
        deviceAdapter.setmDatas(deviceModels);
        rv_home_device.setAdapter(deviceAdapter);
    }


    private void initEvents() {
        tv_home_more.setOnClickListener(this);
    }

    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_home_more:
                //查看更多天气

                break;
        }
    }

    private HomeActivity getCustomActivity() {
        return (HomeActivity) getActivity();
    }

    private void initData() {
        Map<String, String> body = new HashMap<>();
        bOkHttpManager.httpRequest(Constant.RequestType.GET_TIAN_QI, Constant.Http.GET, body, false, new
                TypeToken<Response<WeatherModel, Void>>() {
                }.getType(), true, false);

        //获取实时监测数据
        bOkHttpManager.httpRequest(Constant.RequestType.SELECT_LATEST_STATE, Constant.Http.GET, body, false, new
                TypeToken<Response<List<HomeMonitorModel>, Void>>() {
                }.getType(), true, false);

        //设备控制状态
        bOkHttpManager.httpRequest(Constant.RequestType.SELECT_DEVICE_STATE_NUMBER, Constant.Http.GET, body, false, new
                TypeToken<Response<List<HomeDeviceModel>, Void>>() {
                }.getType(), true, false);

        //设备信息
        bOkHttpManager.httpRequest(Constant.RequestType.SELECT_LATEST_STATE_BY_MAC, Constant.Http.GET, body, false, new
                TypeToken<Response<List<AgileDeviceModel>, Void>>() {
                }.getType(), true, false);
    }

    @Override
    protected void onPostHandle(int requestType, Object response, boolean error, int errorCode, Object obj1, Object obj2) {
        super.onPostHandle(requestType, response, error, errorCode, obj1, obj2);
        if (error) {
            BToast.getInstance().show(getResources().getString(R.string.abnormal));
        } else {
            if (response == null) {
                BToast.getInstance().show(getResources().getString(R.string.datafailure));
            } else {
                if (requestType == Constant.RequestType.SELECT_LATEST_STATE) {
                    Response<List<HomeMonitorModel>, Void> result = (Response<List<HomeMonitorModel>, Void>) response;
                    if (result.isSuccess()) {
                        monitorModels.clear();
                        if (ListUtil.isNotEmpty(result.getData())) {
                            monitorModels.addAll(result.getData());
                        }
                        monitorAdapter.notifyDataSetChanged();
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                }
                if (requestType == Constant.RequestType.SELECT_LATEST_STATE_BY_MAC) {
                    Response<List<AgileDeviceModel>, Void> result = (Response<List<AgileDeviceModel>, Void>)
                            response;
                    if (result.isSuccess()) {
                        if (ListUtil.isNotEmpty(result.getData()) && result.getData().get(0) != null) {
                            tv_home_agile.setText(result.getData().get(0).getHomeDeviceInfoStr
                                    ());
                        }
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                } else if (requestType == Constant.RequestType.GET_TIAN_QI) {
                    Response<WeatherModel, Void> result = (Response<WeatherModel, Void>) response;
                    if (result.isSuccess()) {
                        WeatherModel weather = result.getData();
                        if (weather != null) {
                            tv_home_temperature.setText(weather.tem + "℃");
                            tv_home_weather.setText(weather.wea);
                            tv_home_address_and_data.setText(weather.city + " " + weather.tem_day + " " +
                                    "" + weather
                                    .update_time);
                        }
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                } else if (requestType == Constant.RequestType.SELECT_DEVICE_STATE_NUMBER) {
                    Response<List<HomeDeviceModel>, Void> result = (Response<List<HomeDeviceModel>, Void>) response;
                    if (result.isSuccess()) {
                        deviceModels.clear();
                        if (ListUtil.isNotEmpty(result.getData())) {
                            deviceModels.addAll(result.getData());
                        }
                        deviceAdapter.notifyDataSetChanged();
                    } else {
                        BToast.getInstance().show(result.getMsg());
                    }
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent event) {
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}

